package com.qf.shiro;

import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsAdminService;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.AdminResponseCode;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * AuthorizingRealm : 认证 + 授权
 * @author lixu
 */
@Slf4j
public class AdminAuthorizingRealm extends AuthorizingRealm {

    @Autowired
    private DtsAdminService dtsAdminService;
    @Autowired
    private DtsRoleService dtsRoleService;
    @Autowired
    private DtsPermissionService dtsPermissionService;

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //1：用户对象
        DtsAdmin dtsAdmin = (DtsAdmin) principals.getPrimaryPrincipal();
        //2:角色集合
        Set<String> roles = dtsRoleService.findDtsRoleNameByIds(dtsAdmin.getRoleIds());
        //3:权限集合
        Set<String> perms = dtsPermissionService.findDtsPermsPermissionByRoleIds(dtsAdmin.getRoleIds());

        SimpleAuthorizationInfo simpleAuthorizationInfo =
                new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(roles);
        simpleAuthorizationInfo.setStringPermissions(perms);
        return simpleAuthorizationInfo;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //1:获取用户名及密码
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        String password = new String(usernamePasswordToken.getPassword());

        //2:根据名称查询管理员对象
        DtsAdmin dtsAdmin = dtsAdminService.findDtsAdminByUsername(username);
        if(null == dtsAdmin){
            throw new UnknownAccountException();
        }
        //3:校验密码
        if(!new BCryptPasswordEncoder().matches(password,dtsAdmin.getPassword())){
            throw new IncorrectCredentialsException();
        }
        //4:是否被锁定
        Boolean deleted = dtsAdmin.getDeleted();// 0:false  1:true
        if(deleted){
            //锁定
            throw new LockedAccountException();
        }

        //5:返回值
        AuthenticationInfo authenticationInfo =
                new SimpleAuthenticationInfo(dtsAdmin,password,this.getName());
        return authenticationInfo;
    }
}
